import matplotlib.pyplot as plt
import numpy as np
import matplotlib.cm as cm

# 设置字体
plt.rcParams['font.family'] = 'SimHei'

# 数据
categories = ['生活用品', '家具电器', '科技产品', '卡卷服务', '运动产品', '数码', '潮玩宠物']
group1 = [14.5, 22, 18.7, 23.1, 13.2, 36, 38.5]
group2 = [33.2, 41.2, 26.5, 33.6, 19.8, 31, 32]

# 参数设置
N = len(categories)
angles = np.linspace(0, 2 * np.pi, N, endpoint=False).tolist()  # 每组数据的角度
angles += angles[:1]  # 闭合圆环

# 数据补充闭合
group1 += group1[:1]
group2 += group2[:1]

# 调色板选择：高对比度调色板
cmap = cm.get_cmap('plasma', N * 2)  # 每类别分配相邻的两种颜色

# 创建极坐标图
fig, ax = plt.subplots(figsize=(10, 10), subplot_kw={'projection': 'polar'})

# 设置背景透明
fig.patch.set_alpha(0)  # 整个画布透明
ax.patch.set_alpha(0)   # 极坐标区域透明

# 存储图例项
legend_labels = []

# 绘制柱状图
for i in range(N):
    # 绘制组1柱子
    ax.bar(angles[i], group1[i], width=0.2, color=cmap(i * 2), alpha=0.9, edgecolor='black')
    # 在组1柱子上方添加数值
    ax.text(angles[i], group1[i] + 2, f'{group1[i]}', ha='center', fontsize=10, color='white', fontweight='bold')
    # 为组1添加图例
    legend_labels.append(f'{categories[i]} DCfever')

    # 绘制组2柱子
    ax.bar(angles[i] + 0.2, group2[i], width=0.2, color=cmap(i * 2 + 1), alpha=0.9, edgecolor='black')
    # 在组2柱子上方添加数值
    ax.text(angles[i] + 0.2, group2[i] + 2, f'{group2[i]}', ha='center', fontsize=10, color='white', fontweight='bold')
    # 为组2添加图例
    legend_labels.append(f'{categories[i]} 咸鱼')

# 设置角度与标签
ax.set_theta_offset(np.pi / 2)  # 第一个分类置顶
ax.set_theta_direction(-1)  # 顺时针排列
ax.set_xticks(angles[:-1])
ax.set_xticklabels(categories, fontsize=12, fontweight='bold', color='white')

# 显示更多内圆
max_value = max(max(group1), max(group2))
interval = 5  # 设置更小的间隔
ax.set_yticks(range(0, int(max_value) + interval, interval))
ax.set_yticklabels(range(0, int(max_value) + interval, interval), fontsize=10, color='white')

ax.yaxis.grid(True, linestyle='--', linewidth=0.7, alpha=0.8, color='white')  # 增强网格线视觉效果

# 添加图例，显示16个图例项，2行7列
plt.legend(
    legend_labels, 
    loc='upper center', 
    bbox_to_anchor=(0.5, -0.03), 
    fontsize=10, 
    ncol=7, 
    labelcolor='white', 
    frameon=False  # 去除边框
)

# 图标题
plt.title("咸鱼与DCfever的二手市场规模统计", fontsize=24, fontweight='bold', color='white')

# 保存图像，设置背景透明
plt.savefig('/static/img/shanxing.png', bbox_inches='tight', dpi=600, transparent=True)

# 显示图形
plt.show()

